<?php

namespace App\Http\Controllers\Admin;

use App\DTOS\Admin\RoleEquipDTO;
use App\DTOS\Admin\UserRoleDTO;
use App\DTOS\Admin\UserMemberDTO;
use App\Exports\ExcelExport;
use App\Http\Controllers\Controller;

use App\Models\Customer;
use App\Models\Game\Equip;
use App\Models\Game\OnLinesFristGame;
use App\Models\Game\RoleEquip;
use App\Models\Game\Server;
use App\Models\Game\UserMember;
use App\Models\Game\UserRole;
use App\Services\Game\RoleEquipService;
use App\Services\Game\UserMemberService;
use App\Services\Game\UserRoleService;
use App\Services\RestClientService;
use App\Utils\MyLog;
use App\Utils\ResponseUtil;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Maatwebsite\Excel\Facades\Excel;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

class GameRoleController extends Controller
{
    private Request $request;

    private RestClientService $restClientService;
    private RoleEquipService $roleEquipService;
    private UserRoleService $userRoleService;
    private UserMemberService $userMemberService;

    public function __construct(
        Request $request, RestClientService $restClientService,
        RoleEquipService $roleEquipService,
        UserRoleService $userRoleService,
        UserMemberService $userMemberService
    )
    {
        $this->request = $request;
        $this->restClientService = $restClientService;
        $this->roleEquipService = $roleEquipService;
        $this->userRoleService = $userRoleService;
        $this->userMemberService = $userMemberService;
    }

    private function buildSearchDTO(){
        $gameRoleDTO = new UserRoleDTO($this->request->all());
        $username = $this->request->get('username');
        if ($username){
            $userMemberDTO = new UserMemberDTO(['page'=>1,'limit'=>99999]);
            $userMemberDTO->setUsername($username);
            $paginate = $this->userMemberService->paginate($userMemberDTO);
            $userMemberIds = collect($paginate->items())->pluck('id')->toArray();
            $gameRoleDTO->setMemids($userMemberIds);
        }
        return $gameRoleDTO;
    }

    private function job($v){
        switch($v){
            case 1: return '战士';
            case 2: return '法师';
            case 3: return '射手';
            case 4: return '猎人';
            case 11: return '防御战士';
            case 12: return '狂暴战士';
            case 13: return '守护战士';
            case 21: return '元素法师';
            case 22: return '治疗法师';
            case 23: return '诅咒法师';
            case 31: return '射术猎人';
            case 32: return '隐匿猎人';
            case 33: return '鸿飞猎人';
        }
    }

    public function paginate()
    {
        $res = [];
        $userRoleDTO = new UserRoleDTO(request()->all());
        MyLog::info('UserRoleDTO',$userRoleDTO);

        if ($userRoleDTO->getFields()==='*'){ //没有设置字段
            $userRoleDTO->setFields(['id','nick','memid','createtime','job','sex','isOnline','level','logintime']);
        } else {
            $userRoleDTO->setFields($userRoleDTO->getFields());
        }
        $userRolePaginate = $this->userRoleService->paginate($userRoleDTO);
        $data = $userRolePaginate->items();
        if (empty($data)){
            return ResponseUtil::error('没有数据');
        }
        foreach ($data as &$datum) {
            $member = data_get($datum, 'member');
            if ($member) {
                $member['openid'] = (string)$member['openid'];

                // 查看用户信息
                $customer = Customer::query()->where('id', $member['openid'])->first();
                if ($customer) {
                    $datum['package_no'] = $customer->package_no; // 确保 $customer 存在
                } else {
                    $datum['package_no'] = null; // 如果没有找到客户，设置为 null
                }
            }

            $datum['member'] = $member; // 保持 member 信息
        }
        $res['data'] = $data;
        $res['count'] = $userRolePaginate->total();
        $res['code'] = 0;
        return ResponseUtil::json($res);
    }

    public function detail($id){
        $data = $this->userRoleService->getById($id);
        return ResponseUtil::success($data);
    }

    public function userdetail(){
        $input = request()->only(['gameArea','roleId']);
        $gameArea = (int)data_get($input,'gameArea');
        $roleId = (int)data_get($input,'roleId');

        \Log::info('角色详情查询请求', [
            'gameArea' => $gameArea,
            'roleId' => $roleId,
            'input' => $input
        ]);

        // 使用缓存提升性能，缓存5分钟
        $data = $this->userRoleService->getUserBaseInfo($roleId);

        \Log::info('角色详情查询结果', [
            'roleId' => $roleId,
            'data' => $data ? 'found' : 'not found'
        ]);

        return ResponseUtil::success($data);
    }


    public function rolenewinfo()
    {
        // 获取请求参数
        $input = request()->only(['gameArea', 'createTimeBegin', 'createTimeEnd']);
        $startDate = data_get($input, 'createTimeBegin');
        $endDate = data_get($input, 'createTimeEnd');

        $startDatetime = strtotime(data_get($input, 'createTimeBegin')); // 转换为时间戳
        $endDatetime = strtotime(data_get($input, 'createTimeEnd')); // 转换为时间戳
        global $gameArea; $gameArea = (int) data_get($input,'gameArea');

        // 确保传入日期有效
        if (!$startDate || !$endDate) {
            return ResponseUtil::error('日期范围无效', 400);
        }

        // 获取不重复的 devicecode，并根据创建时间筛选（区间总数口径）
        $uniqueDeviceCodes = Customer::query()
            ->whereNotNull('devicecode')
            ->whereBetween('created_at', [$startDate, $endDate])
            ->distinct('devicecode')
            ->pluck('devicecode');

        // 统计 activeDevice
        $activeDeviceCount = $uniqueDeviceCodes->count();



        // 统计 account 数量（区间内新增账号数）
        $accountCount = UserMember::query()
            ->whereBetween('createtime', [$startDatetime, $endDatetime])
            ->count();

        // 统计 role 数量（根据时间范围）
        $roleCount = UserRole::query()
            ->whereBetween('createtime', [$startDatetime, $endDatetime])
            ->count();


        // 获取当天新注册的账号ID
        $newMemberIds = UserMember::query()
            ->whereBetween('createtime', [$startDatetime, $endDatetime])
            ->pluck('id')
            ->toArray();



        // 获取当天新注册账号创建的角色对应的memid
        $roleCounts = UserRole::query()
            ->whereBetween('createtime', [$startDatetime, $endDatetime])
            ->whereIn('memid', $newMemberIds) //
            ->pluck('memid')
            ->toArray();

        // 获取这些角色对应的openid
        $userMemberModelDay = UserMember::query();
        if (!empty($roleCounts)) {
            $userMemberModelDay->whereIn('id', $roleCounts);
        }
        $memberIds = $userMemberModelDay->pluck('openid')->toArray();

        // 新增有效设备（当天 user_member 里，openid 属于上述 customer 且当日创建）
        $validDeviceCountDays = Customer::query()
            ->whereNotNull('devicecode')
            ->whereIn('id', $memberIds) // 使用正确的变量
            ->whereBetween('created_at', [$startDate, $endDate])
            ->distinct()
            ->pluck('devicecode'); // 只需 pluck，不需要 toArray()

        $validDeviceCount = $validDeviceCountDays->count(); // 直接计算数量


        // 计算 rate
        $rate = $activeDeviceCount > 0 ? ($validDeviceCount / $activeDeviceCount) * 100 : 0;

        // 获取区间内新增的角色ID（用于首次游戏时长统计）
        $newRoleIds = UserRole::query()
            ->whereBetween('createtime', [$startDatetime, $endDatetime])
            ->pluck('id')
            ->toArray();

        // 组装首次游戏时长统计数据
        $fristGameStats = [
            'less_than_1' => 0,
            '1_to_3' => 0,
            '3_to_10' => 0,
            '11_to_31' => 0,
            '31_to_1000000' => 0,
            'total' => 0,
        ];

        // 只统计区间内新增角色的首次游戏时长
        $fristGameDurations = OnLinesFristGame::query()
            ->where("server_id",$gameArea)
            ->get();

        MyLog::info('开始时间时间戳'.json_encode($startDatetime));
        MyLog::info('结束时间时间戳'.json_encode($endDatetime));
        MyLog::info('新增角色ID: ' . json_encode($newRoleIds));
        MyLog::info('首次游戏时长记录数: ' . $fristGameDurations->count());

        foreach ($fristGameDurations as $record) {
            $fristGameTime = $record->fristgametime;

            if ($fristGameTime !== null) {
                $fristGameStats['total']++;

                if ($fristGameTime < 1) {
                    $fristGameStats['less_than_1']++;
                } elseif ($fristGameTime >= 1 && $fristGameTime < 3) {
                    $fristGameStats['1_to_3']++;
                } elseif ($fristGameTime >= 3 && $fristGameTime < 10) {
                    $fristGameStats['3_to_10']++;
                } elseif ($fristGameTime >10 && $fristGameTime <30) {
                    $fristGameStats['11_to_31']++;
                } elseif ($fristGameTime >30) {
                    $fristGameStats['31_to_1000000']++;
                }
            }
        }

        // 组装返回数据格式
        $firstPlayRows = [
            ['label' => '1分钟以内', 'count' => $fristGameStats['less_than_1'], 'rate' => $fristGameStats['total'] > 0 ? number_format(($fristGameStats['less_than_1'] / $fristGameStats['total']) * 100, 2) : '0.00'],
            ['label' => '1-3分钟', 'count' => $fristGameStats['1_to_3'], 'rate' => $fristGameStats['total'] > 0 ? number_format(($fristGameStats['1_to_3'] / $fristGameStats['total']) * 100, 2) : '0.00'],
            ['label' => '3-10分钟', 'count' => $fristGameStats['3_to_10'], 'rate' => $fristGameStats['total'] > 0 ? number_format(($fristGameStats['3_to_10'] / $fristGameStats['total']) * 100, 2) : '0.00'],
            ['label' => '10-30分钟', 'count' => $fristGameStats['11_to_31'], 'rate' => $fristGameStats['total'] > 0 ? number_format(($fristGameStats['11_to_31'] / $fristGameStats['total']) * 100, 2) : '0.00'],
            ['label' => '30分钟以上', 'count' => $fristGameStats['31_to_1000000'], 'rate' => $fristGameStats['total'] > 0 ? number_format(($fristGameStats['31_to_1000000'] / $fristGameStats['total']) * 100, 2) : '0.00'],
        ];
        $res=[];
        // 组装最终返回数据（按日维度汇总）
        $newUserRows = [];
        $start = \Carbon\Carbon::parse($startDate);
        $end = \Carbon\Carbon::parse($endDate);
        for ($date = $start->copy(); $date->lt($end); $date->addDay()) {
            $dayStart = $date->copy()->startOfDay()->format('Y-m-d H:i:s');
            $dayEnd = $date->copy()->endOfDay()->format('Y-m-d H:i:s');

            MyLog::info('开始日期'.json_encode($dayStart));
            MyLog::info('结束日期'.json_encode($dayEnd));

            $dayStarttime = strtotime($dayStart); // 转换为时间戳
            $dayEndtime = strtotime($dayEnd); // 转换为时间戳
            // 当天不重复的设备（基于 customer.devicecode，按天新增）
            $uniqueDeviceCodesDay = Customer::query()
                ->whereNotNull('devicecode')
                ->whereBetween('created_at', [$dayStart, $dayEnd])
                ->distinct('devicecode')
                ->pluck('devicecode');
            $activeDeviceCountDay = $uniqueDeviceCodesDay->count();

            // 当天这些设备对应的用户集合
            $customerIdsDay = Customer::query()
                ->whereIn('devicecode', $uniqueDeviceCodesDay)
                ->pluck('id')
                ->toArray();
            MyLog::info('激活设备账号ID'.json_encode($customerIdsDay));



            // 新增账号（当天创建的 user_member 数）
            $accountCountDay = UserMember::query()
                ->whereBetween('createtime', [$dayStarttime, $dayEndtime])
                ->count();

            // 获取当天新注册的账号ID
            $newMemberIds = UserMember::query()
                ->whereBetween('createtime', [$dayStarttime, $dayEndtime])
                ->pluck('id')
                ->toArray();

            // 新增角色（当天新注册账号创建的角色数）
            $roleCountDay = UserRole::query()
                ->whereBetween('createtime', [$dayStarttime, $dayEndtime])
                ->whereIn('memid', $newMemberIds) // 只统计当天新注册账号创建的角色
                ->count();

            // 获取当天新注册账号创建的角色对应的memid
            $roleCounts = UserRole::query()
                ->whereBetween('createtime', [$dayStarttime, $dayEndtime])
                ->whereIn('memid', $newMemberIds) // 只统计当天新注册账号创建的角色
                ->pluck('memid')
                ->toArray();

            // 获取当天新注册账号创建的角色对应的memid
            $roledayCounts = UserRole::query()
                ->whereBetween('createtime', [$dayStarttime, $dayEndtime])
                ->pluck('id');

            // 获取这些角色对应的openid
            $userMemberModelDay = UserMember::query();
            if (!empty($roleCounts)) {
                $userMemberModelDay->whereIn('id', $roleCounts);
            }
            $memberIds = $userMemberModelDay->pluck('openid')->toArray();

            // 新增有效设备（当天 user_member 里，openid 属于上述 customer 且当日创建）
            $validDeviceCountDays = Customer::query()
                ->whereNotNull('devicecode')
                ->whereIn('id', $memberIds) // 使用正确的变量
                ->whereBetween('created_at', [$dayStart, $dayEnd])
                ->pluck('devicecode'); // 只需 pluck，不需要 toArray()

            // 记录日志
            MyLog::info('有效设备账号ID: ' . json_encode($memberIds)); // 确保输出正确的变量
            $validDeviceCountDay = $validDeviceCountDays->count(); // 直接计算数量
            // 转化率
            $rateDay = $activeDeviceCountDay > 0 ? number_format(($validDeviceCountDay / $activeDeviceCountDay) * 100, 2) : '0.00';

            $newUserRows[] = [
                'date' => $date->format('Y-m-d'),
                'activeDevice' => $activeDeviceCountDay,
                'validDevice' => $validDeviceCountDay,
                'account' => $accountCountDay,
                'role' => $roledayCounts->count(),
                'rate' => $rateDay,
            ];
        }
        $res['firstPlayRows'] =$firstPlayRows;
        $res['newUserRows'] =$newUserRows;
        // 区间汇总数据，供顶部展示
        $res['statData'] = [
            'activeDevice' => $activeDeviceCount,
            'validDevice' => $validDeviceCount,
            'account' => $accountCount,
            'role' => $roleCount,
            'rate' => number_format($rate, 2),
        ];

        return ResponseUtil::success($res); // 返回统计结果
    }


    //搜索单个角色
    public function searchOne(){
        $data = array_only($this->request->all(),['roleId','roleName','zoneId']);
        $zoneId = data_get($data,'zoneId');
        $roleId = data_get($data,'roleId');
        $roleName = data_get($data,'roleName');
        $gameRoleDTO = new UserRoleDTO(['limit'=>1]);
        if ($zoneId){
            $gameRoleDTO->setZoneId($zoneId);
        }
        if ($roleName){
            $gameRoleDTO->setNick($roleName);
        }
        if ($roleId){
            $gameRoleDTO->setId($roleId);
        }
        global $gameArea;

        $paginate = $this->userRoleService->paginate($gameRoleDTO);
        $data = collect($paginate->items())->toArray();
        if (!empty($data)) {
            $data = $data[0];//分页 limit 1
            $roleId = $data['id'];
            $roleStall = callRpc('/RoleStallService/getById',['roleId'=>$roleId],['gameArea'=>$gameArea]); //当前摆摊数据
            $sell_item_list = data_get($roleStall,'sell_item_list.data');

            //转换 整型超过js范围的数据,否则浏览器显示错误
            foreach ($data['bag'] as &$datum) {
                $datum['base']['uniqueid'] = '"' . strval($datum['base']['uniqueid']) . '"';
            }

         //   foreach ($data['combat']['combat_equip'] as &$datum) {
         //       $datum['base']['uniqueid'] = '"' . strval($datum['base']['uniqueid']) . '"';
         //   }

            foreach ($data['warehouse'] as &$datum) {
                $datum['base']['uniqueid'] = '"' . strval($datum['base']['uniqueid']) . '"';
            }
            foreach ($data['warehouse'] as &$datum) {
                $datum['base']['uniqueid'] = '"' . strval($datum['base']['uniqueid']) . '"';
            }
            $data['sell_item_list'] = $sell_item_list;
            if (is_array($data['sell_item_list'])) {
                foreach ($data['sell_item_list'] as &$datum) {
                    if (isset($datum['base']['uniqueid'])) {
                        $datum['base']['uniqueid'] = '"' . strval($datum['base']['uniqueid']) . '"';
                    }
                }
                unset($datum); // 取消引用
            }

            $data['petList'] = data_get($data,'pet.petList',[]);
            return ResponseUtil::success($data);
        } else {
            return ResponseUtil::error("无此角色");
        }
    }

    public function export(){

        $userRoleDTO = new UserRoleDTO(request()->all());
        if ($userRoleDTO->getFields()==='*'){ //没有设置字段
            $userRoleDTO->setFields(['id','nick','memid','createtime','logintime','job','sex','isOnline','level']);
        } else {
            $userRoleDTO->setFields($userRoleDTO->getFields());
        }
        $paginate = $this->userRoleService->paginate($userRoleDTO);
        $excelRows = [
            ['区服ID','账号','游戏账号ID','官网账号ID','角色ID','角色名','创建时间','登录时间','职业','性别','等级','包号']
        ];
        foreach($paginate->items() as $datum){ //['id','username','openid','areaid'] 账号名 , 游戏ID, 官网张阿红ID

            $member = data_get($datum, 'member');
            if ($member) {
                $member['openid'] = (string)$member['openid'];

                // 查看用户信息
                $customer = Customer::query()->where('id', $member['openid'])->first();
                if ($customer) {
                    $datum['package_no'] = $customer->package_no; // 确保 $customer 存在
                } else {
                    $datum['package_no'] = null; // 如果没有找到客户，设置为 null
                }
            }


            $excelRows[] = [
                data_get($datum,'member.areaid'),
                data_get($datum,'member.username'),
                data_get($datum,'member.id'),
                "'".data_get($datum,'member.openid'),
                data_get($datum,'id'),
                data_get($datum,'nick'),
                data_get($datum,'createtime') ? date("Y-m-d H:i:s",data_get($datum,'createtime')): '无',
                data_get($datum,'logintime') ? date("Y-m-d H:i:s",data_get($datum,'logintime')): '无',
                self::job(data_get($datum,'job')),
                data_get($datum,'sex')==1 ? '男':'女',
                data_get($datum,'level'),
                data_get($datum,'package_no'),

            ];
        }
        $excel = new ExcelExport($excelRows);
        return Excel::download($excel, '游戏角色.xlsx');
    }

    private function equipStaBuildRes(RoleEquipDTO $roleEquipDTO,$index ){
        $paginate=[];

        if($index===1){
            $paginate = $this->roleEquipService->groupPaginate($roleEquipDTO);
        }else{
        $paginate = $this->roleEquipService->paginate($roleEquipDTO);

        }
        $data = $paginate->items();
        $memIds = collect($data)->pluck('mem_id')->unique()->toArray();
        $roleIds = collect($data)->pluck('role_id')->unique()->toArray();
        $equipIds = collect($data)->pluck('equip_id')->unique()->toArray();
        $members = $this->userMemberService->getByIds($memIds);
        $userRoles = $this->userRoleService->getByIds($roleIds);
        $equips = Equip::query()->whereIn('id',$equipIds)->get()->toArray();
        foreach ($data as &$datum) {
            $datum['member'] = collect($members)->where('id',$datum['mem_id'])->first();
            $datum['role'] = collect($userRoles)->where('id',$datum['role_id'])->first();
            $datum['equip'] = collect($equips)->where('id',$datum['equip_id'])->first();
        }

        $res = [];
        $res['code'] = 0;
        $res['data'] = $data;
        $res['count'] = $paginate->total();
        return $res;
    }

    //角色列表查询 (使用物品名称,统计该物品数量)
    public function equipSta(){
        $index=0;
        $roleEquipDTO = new RoleEquipDTO(request()->all());
        $res = $this->equipStaBuildRes($roleEquipDTO,$index);
        return ResponseUtil::json($res);
    }

    //角色列表查询 (使用物品名称,统计该物品数量)
    public function equipStahb(){
        $index=1;
        $roleEquipDTO = new RoleEquipDTO(request()->all());
        $res = $this->equipStaBuildRes($roleEquipDTO,$index);
        return ResponseUtil::json($res);
    }

    public function equipStaExport(){
        $roleEquipDTO = new RoleEquipDTO(request()->all());
        $roleEquipDTO->setLimit(100000);
        $res = $this->equipStaBuildRes($roleEquipDTO);
        $data = data_get($res,'data',[]);
        $spreadSheet = new Spreadsheet();

        $sheet = $spreadSheet->getActiveSheet();// 获取当前激活的工作表
        $sheet->setCellValue('A1', '区服ID');
        $sheet->setCellValue('B1', '账号');
        $sheet->setCellValue('C1', '角色ID');
        $sheet->setCellValue('D1', '角色名');
        $sheet->setCellValue('E1', '角色等级');
        $sheet->setCellValue('F1', '物品ID');
        $sheet->setCellValue('G1', '唯一ID');
        $sheet->setCellValue('H1', '物品名称');
        $sheet->setCellValue('I1', '物品数量');

        $rowNum = 2;
        foreach($data as $key=>$item){
            $member = data_get($item,'member');

            $sheet->setCellValue('A'.$rowNum, data_get($member,'areaid'));
            $sheet->setCellValue('B'.$rowNum, data_get($member,'username'));
            $sheet->setCellValue('C'.$rowNum, $item['role_id']);
            $sheet->setCellValue('D'.$rowNum, data_get($item,'role.nick'));
            $sheet->setCellValue('E'.$rowNum, data_get($item,'role.level'));
            $sheet->setCellValue('F'.$rowNum, $item['equip_id']);
            $sheet->setCellValue('G'.$rowNum, "'".$item['equip_uuid']);
            $sheet->setCellValue('H'.$rowNum, data_get($item,'equip.name'));
            $sheet->setCellValue('I'.$rowNum, data_get($item,'count'));

            $rowNum++;
        }

        $writer = new Xlsx($spreadSheet);
        ob_start(); //打开缓冲区
        $writer->save('php://output');
        $title = urlencode('全服物品查询');
        header("Content-Disposition: attachment; filename=.xlsx; filename*=utf-8''$title.xlsx");
        return $xlsdata = ob_get_contents();
    }

    public function ti(){ //角色踢下线
        $input = request()->only(['gameArea','roleId','roles']);
        MyLog::info("传入的数据".json_encode($input));

        try {
            $gameArea = (int)data_get($input,'gameArea');
            $roleId = (int)data_get($input,'roleId');
            $roleIds = explode("\n", data_get($input, 'roles'));

                // 过滤掉空字符串
            $roleIds = array_filter($roleIds, function($role) {
                return trim($role) !== '';
            });
            MyLog::info("传入的".json_encode($roleIds));
            $row = Server::query()->where('can_push',1)->where("server_id",$gameArea)->first();
            $pushUrl = data_get($row,'push_url');
            MyLog::info('踢人的接口'.json_encode($pushUrl));
            if(count($roleIds)>0){
                MyLog::info("处理之后".json_encode($roleIds));

                foreach ($roleIds as $roleId) {

                    $requestBody = [
                        'RoleId'=>intval($roleId)
                    ];
                    MyLog::info("请求的参数".json_encode($requestBody));

                    $response = Http::withHeaders(['Content-Type'=>'application/json'])
                        ->post($pushUrl.'/Api/Role/KickRole',$requestBody);
                    $body = json_decode($response->body(),true);
                    $RetCode = data_get($body,'RetCode');
                    if ($RetCode == 0 ) {
                        MyLog::info("踢人成功".json_encode($RetCode));

                        continue;
                    }else if($RetCode == 3){
                        MyLog::info("未找到角色".json_encode($RetCode));
                        continue;
                    } else {
                        MyLog::info("错误代码".json_encode($RetCode));
                        continue;

                    }
                    // 在每次循环后sleep 0.5毫秒
                    usleep(1000);
                }
                return ResponseUtil::success();

            }else{
                $requestBody = [
                    'RoleId'=>$roleId
                ];
                $response = Http::withHeaders(['Content-Type'=>'application/json'])
                    ->post($pushUrl.'/Api/Role/KickRole',$requestBody);
                $body = json_decode($response->body(),true);
                $RetCode = data_get($body,'RetCode');
                MyLog::info("返回结果".json_encode($RetCode));

                if ($RetCode == 0 ) {
                    return ResponseUtil::success();
                }else if($RetCode == 3){
                    throw new \Exception('未找到角色',3);
                } else {
                    throw new \Exception('错误代码:' . $RetCode);
                }

            }

        }catch (\Exception $e){
            return ResponseUtil::error($e->getMessage());
        }
    }


    public function editCoordinates(){ //角色坐标数据充值
        $input = request()->only(['content','roleid','gameArea']);
        try {
            $gameArea = data_get($input,'gameArea');
            $content = data_get($input,'content');
            $roleId = data_get($input,'roleid');
            $MapID='';
            $PosX='';
            $PosY='';
            if($content ){
                $contentParts = explode('*',$content);
                if (count($contentParts) === 3) {
                    $MapID = $contentParts[0];
                    $PosX= $contentParts[1];
                    $PosY= $contentParts[2];
                }
            }
            $row = Server::query()->where('can_push',1)->where("server_id",$gameArea)->first();
            MyLog::info('服务器信息'.json_encode($row));
            $pushUrl = data_get($row,'push_url');
            $requestBody = [
                'RoleId'=>intval($roleId),
                'MapID'=>intval($MapID),
                'PosX'=>intval($PosX),
                'PosY'=>intval($PosY),
                'Sign'=>"10086"

            ];
            MyLog::info('返回结果'.json_encode($requestBody));
            $response = Http::withHeaders(['Content-Type'=>'application/json'])
                ->post($pushUrl.'/Api/Role/ChangePosition',$requestBody);
            $body = json_decode($response->body(),true);
            $RetCode = data_get($body,'RetCode');
            MyLog::info('返回结果'.json_encode($RetCode));
            if ($RetCode !== NULL &&$RetCode == 0 ) {
                return ResponseUtil::success();
            }else {
                throw new \Exception('错误代码:' . $RetCode);
            }
        }catch (\Exception $e){
            return ResponseUtil::error($e->getMessage());
        }
    }

    public function checkRoleExists() { //检测角色ID是否存在
        $roleIds = strArrToIntArr(explode(',',request()->get('roleIdsStr')));
        $notExistsIds = $this->userRoleService->checkRoleExists($roleIds);
        return ResponseUtil::success([
            'notExistsIds'=>$notExistsIds
        ]);
    }

    //导出重复的UUID列表
    public function exportRepeatedUuid()
    {
        $gameArea = request()->get('gameArea');
        $array = RoleEquip::query()->selectRaw("equip_uuid,count(*) as repeat_num")->where('server_id',$gameArea)
            ->groupBy('equip_uuid')->havingRaw("count(*) > 1")->get()->toArray();
        $excelRows = [
            ['物品唯一ID','重复次数']
        ];
        foreach($array as $datum){
            $excelRows[] = [
                "'".$datum['equip_uuid'],
                $datum['repeat_num'] ?? null,
            ];
        }
        $excel = new ExcelExport($excelRows);
        return Excel::download($excel, '重复的物品唯一ID.xlsx');
    }

    public function repeatedUuidExists(){
        $exists = RoleEquip::query()->selectRaw("equip_uuid,count(*) as repeat_num")
            ->groupBy('equip_uuid')->havingRaw("count(*) > 1")->exists();

        return ResponseUtil::success(['exists'=>$exists]);


    }


}
